package com.fanttec.common.websocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.util.List;
import java.util.Objects;
@Slf4j
public class WebSocketChannelInterceptor implements ChannelInterceptor {
	private Logger logger = LoggerFactory.getLogger(WebSocketChannelInterceptor.class);
	/**
	   * 发送消息前可以做的业务
	   *
	   * @param message
	   * @param channel
	   * @return
	   */
	@Override
	  public Message<?> preSend(Message<?> message, MessageChannel channel) {
	      StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	      if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {
	    	  List<String> header = accessor.getNativeHeader("Authorization");
              if (header != null) {
                  log.info(header.toString());
              }
          }
		  // 报错 No enum constant org.springframework.messaging.simp.stomp.StompCommand.SUBSCRIBE
		 // else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
	      else if (accessor != null && "SUBSCRIBE".equals(Objects.requireNonNull(accessor.getCommand()).toString())) {
			  logger.info(String.valueOf(accessor));
		  }
		//不是首次连接，已经登陆成功
	      return message;
	  }

}
